package com.carnation.job;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.carnation.service.FileService;
import com.carnation.service.Ftp;
import com.carnation.service.impl.FTPServerImpl;
import com.carnation.service.impl.FileServiceImpl;
import com.carnation.service.impl.SFTPServerImpl;
import com.carnation.utils.MenuFileUtril;

public class UploadJob implements Job{
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		Logger logger = Logger.getLogger(UploadJob.class);
		MenuFileUtril menuFileUtril = new MenuFileUtril();
		FileService fileService = new FileServiceImpl();
		String remotePath = menuFileUtril.getFTPStorePath();
		Ftp ftp = null;
		String protocl = menuFileUtril.getFTPProtocol();
		if(protocl.toLowerCase().equals("sftp")){
			ftp = new SFTPServerImpl();
		}
		else if(protocl.toLowerCase().equals("ftp")){
			ftp = new FTPServerImpl();
		}
		else{
			logger.info("尚不支持该协议:" + protocl);
			return ;
		}
		List<String> catalogIdList = fileService.getAllCatalogId();
		Map<String, List<String>> diffMap = new HashMap<String,List<String>>(); 
		for(String catalogId : catalogIdList){
			boolean flag = ftp.mkdir(remotePath, catalogId);
			if(flag){
//				创建目录成功，即remote中没有该文件夹，把所有这些文件吧
				Map<String,Long> diff = fileService.getFileNameListByCatalogId(catalogId);
				diffMap.put(catalogId, new ArrayList<String>(diff.keySet()));
			}
			else{
				Map<String,Long> localFileNames = fileService.getFileNameListByCatalogId(catalogId);
				Map<String,Long> remoteFileNames = ftp.findRegularFileList(catalogId);
				List<String> diff = new ArrayList<String>();
				for(String localFile : localFileNames.keySet()){
					if(!remoteFileNames.keySet().contains(localFile)){
						diff.add(localFile);
					}
					else{
						if(remoteFileNames.get(localFile).longValue() != localFileNames.get(localFile).longValue()){
//							大小不同的情况
							diff.add(localFile);
						}
					}
				}
				if(diff.size() > 0){
					diffMap.put(catalogId, diff);
				}
			}
		}
		if(diffMap.size() == 0){
			logger.info("未发现用户有上传新文件");
		}
		else{
			for(String key : diffMap.keySet()){
				String directory = remotePath + "/" + key;
				List<String> localFile = diffMap.get(key);
				File file = new File(menuFileUtril.getRootPath(),key);
				for(int i=0;i<localFile.size();i++){
					File f = new File(file.getAbsolutePath(), localFile.get(i));
					String localFileName = f.getAbsolutePath();
					ftp.uploadFile(directory, localFileName,localFile.get(i));	
				}
			}
			logger.info("上传完成");
		}
	}
}
